extends CanvasLayer

@export var actor_model_list : Array[PackedScene]
@onready var check_click_area : Area2D = $ChceckClickArea
@onready var actor_list : HBoxContainer = $ActorList
@onready var begin_button : Button = $BeginButton
var select_actor : Node2D

func _ready():
	begin_button.button_up.connect(_on_begin_game)
	for pre_model in actor_model_list :
		var model = pre_model.duplicate()
		var actor = model.instantiate()
		actor_list.add_child(actor)
		actor.custom_button_up.connect(_on_clike_event)
	pass

func _process(_delta):
	if select_actor :
		select_actor.global_position = select_actor.get_global_mouse_position()
	check_click_area.global_position = check_click_area.get_global_mouse_position()
	pass

func _input(event):
	if event as InputEventMouseButton :
		if event.is_pressed() :
			if check_click_area.has_overlapping_bodies() :
				var click_target : Array[Node2D] = check_click_area.get_overlapping_bodies()
				if click_target[0].get_collision_layer_value(2) :
					_move_actor(click_target[0])
		if event.is_pressed() :
			if select_actor :
				var grid = owner.grid
				var xy = grid._get_xy()
				if grid._check_in_grid(xy) :
					select_actor.global_position = owner.grid._get_centor_pos(xy)
				select_actor = null
				actor_list.show()
	pass

func _move_actor(click_target : Node2D) :
	select_actor = click_target

func _on_clike_event(pre_actor_model) :
	actor_list.hide()
	var actor = pre_actor_model._create_actor()
	get_tree().current_scene._add_actor(actor)
	_move_actor(actor)
	pass

func _on_begin_game() :
	if begin_button.is_hovered() :
		get_tree().current_scene.is_paused = false
		hide()
	pass
